# Create your views here.
import json
import random
import re
import traceback

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth import logout
from django.http import HttpResponse, JsonResponse
from django.views import View
from django_redis import get_redis_connection
import logging

from ajia08.libs.captcha.captcha import captcha
# 非异步,调用这里
from ajia08.libs.yuntongxun.sms import CCP
# 异步,调用这里
from celery_tasks.SMS.tasks import ccp_send_sms_code

logger = logging.getLogger('ajia08')


# 短信验证码视图
class SmsCodeView(View):

    def post(self, request):
        """
        xxx
        :param request:
        {'mobile':手机号, 'id': 图形验证码编号,'text':图形验证码内容}
        :return:{'errno': 状态码, 'errmsg':状态信息}
        """
        # 1.接收参数
        request_dict = json.loads(request.body.decode())
        mobile = request_dict.get('mobile')
        id = request_dict.get('id')
        text = request_dict.get('text')
        print("mobile:", mobile)
        print("id:", id)
        print("text:", text)
        # 2.校验参数(单个+整体)
        if not all([mobile, id, text]):
            return JsonResponse({'errno': "4103",
                                 'errmsg': '参数错误'})
        # 3.参数不正确,直接返回
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': "4103",
                                 'errmsg': '参数错误'})
        # 4.参数正确,从redis提取图形验证
        redis_conn = get_redis_connection('verify_code')

        image_code_server = redis_conn.get('image_%s' % id)
        # 5.判断图形验证码是否过期
        if not image_code_server:
            return JsonResponse({"errno": "4103",
                                 "errmsg": "参数错误"})
        # 5.删除和对比图形验证码
        try:
            redis_conn.delete('image_%s' % id)
        except Exception as e:
            logger.error(traceback.format_exc())
            return JsonResponse({"errno": "4001",
                                 "errmsg": "数据库查询错误"})
        # 转码
        image_code_server = image_code_server.decode()
        print(image_code_server)

        if text.lower() != image_code_server.lower():
            return JsonResponse({"errno": "4103",
                                 "errmsg": "参数错误"})
        # 6.生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print("短信验证码", sms_code)
        # 7.保存短信验证码日志
        logger.info(sms_code)

        # pl = redis_conn.pipeline()
        # pl.setex('send_flag_%s' % mobile, 60, sms_code)
        # pl.setex('sms_%s' % mobile, 300, 1)
        # pl.execute()
        redis_conn.setex('sms_%s' % mobile, 300, sms_code)

        # 往 redis 中写入一个数据, 设置验证码是否过期
        # 给写入的数据设置为60s,如果false则为过期,则会获取不到.
        # redis_conn.setex('send_flag_%s' % mobile, 60, 1)

        # 8.发送短信验证码
        # 发送短信验证码
        result = CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # print('发送短信验证码的结果:', result)
        # 异步发送短信验证码,需关闭以下注释;
        # result = ccp_send_sms_code.delay(mobile, sms_code)
        print('发送短信验证码的结果:', result)

        # 9.响应结果
        return JsonResponse({"errno": "0",
                             "errmsg": "发送成功"})

# 图形验证码视图
class ImageCodeView(View):
    """创建图形验证码类视图"""

    def get(self, request):
        """
        生成图形验证码
        :param request: 请求参数 {'cur':验证码编号,'pre': 上一次验证码编号(非必传)}
        :return:image,生成图片返回给前端;
        """
        # 1.生成图形验证码
        cur = request.GET.get('cur')
        pre = request.GET.get('pre')
        text, image = captcha.generate_captcha()
        print('cur', cur)
        print('pre', pre)
        print(text)
        # 2.连接redis,保存数据到redis;
        try:
            redis_conn = get_redis_connection('verify_code')
            redis_conn.setex('image_%s' % cur, 300, text)
        except Exception as e:
            logger.error(traceback.format_exc())
            return JsonResponse({"errno": "4001",
                                 "errmsg": "数据库查询错误"})

        # 3.返回图片到前端
        return HttpResponse(image,
                            content_type="image/jpg")
